function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { Node, Edge } from '@antv/x6';
import ELNode from "../node";
import { ELEndNode, ELVirtualNode } from "../utils";
import { ConditionTypeEnum, LITEFLOW_EDGE, NODE_TYPE_INTERMEDIATE_END, NodeTypeEnum } from "../../constant";
import NodeOperator from "./node-operator";

/**
 * 条件编排操作符：IF。
 *
 * 例如一个条件编排(IF)示例：
 * (1) EL表达式语法：IF(x, a)
 * (2) JSON表示形式：
 * {
    type: ConditionTypeEnum.IF,
    condition: { type: NodeTypeEnum.IF, id: 'x' },
    children: [
      { type: NodeTypeEnum.COMMON, id: 'a' }
    ],
  }
  * (3) 通过ELNode节点模型进行表示的组合关系为：
                                          ┌─────────────────┐
                                      ┌──▶│  NodeOperator   │
  ┌─────────┐    ┌─────────────────┐  │   └─────────────────┘
  │  Chain  │───▶│    IfOperator   │──┤   ┌─────────────────┐
  └─────────┘    └─────────────────┘  └──▶│  NodeOperator   │
                                          └─────────────────┘
 */
var IfOperator = /*#__PURE__*/function (_ELNode) {
  _inherits(IfOperator, _ELNode);
  var _super = _createSuper(IfOperator);
  function IfOperator(parent, condition, children, properties) {
    var _this;
    _classCallCheck(this, IfOperator);
    _this = _super.call(this);
    _defineProperty(_assertThisInitialized(_this), "type", ConditionTypeEnum.IF);
    _defineProperty(_assertThisInitialized(_this), "parent", void 0);
    _defineProperty(_assertThisInitialized(_this), "condition", new NodeOperator(_assertThisInitialized(_this), NodeTypeEnum.IF, 'x'));
    _defineProperty(_assertThisInitialized(_this), "children", []);
    _defineProperty(_assertThisInitialized(_this), "properties", void 0);
    _defineProperty(_assertThisInitialized(_this), "startNode", void 0);
    _defineProperty(_assertThisInitialized(_this), "endNode", void 0);
    _this.parent = parent;
    if (condition) {
      _this.condition = condition;
    }
    if (children) {
      _this.children = children;
    }
    _this.properties = properties;
    return _this;
  }

  /**
   * 创建新的节点
   * @param parent 新节点的父节点
   * @param type 新节点的子节点类型
   */
  _createClass(IfOperator, [{
    key: "toCells",
    value:
    /**
     * 转换为X6的图数据格式
     */
    function toCells() {
      var _this2 = this;
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      this.resetCells();
      var condition = this.condition,
        _this$children = this.children,
        children = _this$children === void 0 ? [] : _this$children,
        cells = this.cells;
      condition.toCells({
        shape: NodeTypeEnum.IF
      });
      var start = condition.getStartNode();
      start.setData({
        model: condition,
        toolbar: {
          prepend: true,
          append: false,
          delete: true,
          replace: true,
          collapse: true
        }
      }, {
        overwrite: true
      });
      this.startNode = start;
      start = condition.getEndNode();
      if (!this.collapsed) {
        var end = Node.create({
          shape: NODE_TYPE_INTERMEDIATE_END,
          attrs: {
            label: {
              text: ''
            }
          }
        });
        end.setData({
          model: new ELEndNode(this),
          toolbar: {
            prepend: false,
            append: true,
            delete: true,
            replace: true
          }
        }, {
          overwrite: true
        });
        cells.push(this.addNode(end));
        this.endNode = end;
        var _children = _slicedToArray(children, 2),
          trueNode = _children[0],
          falseNode = _children[1];
        [trueNode, falseNode].forEach(function (item, index) {
          var next = item || NodeOperator.create(_this2, NodeTypeEnum.VIRTUAL, ' ');
          next.toCells(options);
          var nextStartNode = next.getStartNode();
          cells.push(Edge.create({
            shape: LITEFLOW_EDGE,
            source: start.id,
            target: nextStartNode.id,
            label: index ? 'false' : 'true'
          }));
          var nextEndNode = next.getEndNode();
          cells.push(Edge.create({
            shape: LITEFLOW_EDGE,
            source: nextEndNode.id,
            target: end.id,
            label: ' '
          }));
          if (!item) {
            nextStartNode.setData({
              model: new ELVirtualNode(_this2, index, next),
              toolbar: {
                prepend: false,
                append: false,
                delete: false,
                replace: true
              }
            }, {
              overwrite: true
            });
            cells.push(_this2.addNode(nextStartNode));
          }
        });
      }
      return this.getCells();
    }

    /**
     * 在后面添加子节点
     * @param newNode 子节点
     * @param index 指定位置：可以是索引，也可以是兄弟节点
     */
  }, {
    key: "appendChild",
    value: function appendChild(newNode, index) {
      newNode.parent = this;
      if (this.children) {
        // 尝试在父节点中添加新节点
        if (typeof index === 'number') {
          // 1. 如果有索引
          // this.children.splice(index, this.children[index] ? 1: 0, newNode);
          this.children[index <= 1 ? index : 1] = newNode;
          return true;
        }
        if (index) {
          // 2. 如果有目标节点
          var _index = this.children.indexOf(index);
          if (_index !== -1) {
            // this.children.splice(_index + 1, this.children[_index] ? 1: 0, newNode);
            this.children[_index <= 1 ? _index : 1] = newNode;
            return true;
          }
          // 3. 如果是在condition之后追加
          if (this.condition === index) {
            return this.appendChild(newNode, 0);
          }
        }
        // 4. 否则直接插入
        this.children.push(newNode);
        return true;
      }
      return false;
    }

    /**
     * 在后面添加子节点
     * @param newNode 子节点
     * @param index 指定位置：可以是索引，也可以是兄弟节点
     */
  }, {
    key: "prependChild",
    value: function prependChild(newNode, index) {
      newNode.parent = this;
      if (this.children) {
        // 尝试在父节点中添加新节点
        if (typeof index === 'number') {
          // 1. 如果有索引
          // this.children.splice(index, this.children[index] ? 1: 0, newNode);
          this.children[index] = newNode;
          return true;
        }
        if (index) {
          // 2. 如果有目标节点
          var _index = this.children.indexOf(index);
          if (_index !== -1) {
            // this.children.splice(_index, this.children[_index] ? 1: 0, newNode);
            this.children[_index] = newNode;
            return true;
          }
          if (this.condition === index) {
            // 3. 如果是在condition之前追加
            return this.prepend(newNode);
          }
        }
        // 4. 否则直接插入
        this.children.splice(0, this.children[0] ? 1 : 0, newNode);
        return true;
      }
      return false;
    }

    /**
     * 转换为EL表达式字符串
     */
  }, {
    key: "toEL",
    value: function toEL() {
      var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      if (prefix) {
        return "".concat(prefix, "IF(\n").concat([this.condition.toEL("".concat(prefix, "  "))].concat(_toConsumableArray(this.children.filter(function (x) {
          return x;
        }).map(function (x) {
          return x.toEL("".concat(prefix, "  "));
        }))).join(', \n'), "\n").concat(prefix, ")").concat(this.propertiesToEL());
      }
      return "IF(".concat([this.condition.toEL()].concat(_toConsumableArray(this.children.filter(function (x) {
        return x;
      }).map(function (x) {
        return x.toEL();
      }))).join(', '), ")").concat(this.propertiesToEL());
    }
  }], [{
    key: "create",
    value: function create(parent, type) {
      var newNode = new IfOperator(parent);
      newNode.appendChild(NodeOperator.create(newNode, type));
      return newNode;
    }
  }]);
  return IfOperator;
}(ELNode);
export { IfOperator as default };